package top.yaofengqiao.springcloudsimple.payment.biz.domain.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.yaofengqiao.springcloudsimple.common.constant.ResponseCode;
import top.yaofengqiao.springcloudsimple.common.util.AppException;
import top.yaofengqiao.springcloudsimple.payment.biz.domain.pay.service.IPaymentClient;
import top.yaofengqiao.springcloudsimple.payment.biz.domain.pay.model.req.PaymentApplyRequest;
import top.yaofengqiao.springcloudsimple.payment.biz.domain.pay.model.res.PaymentApplyResult;
import top.yaofengqiao.springcloudsimple.payment.biz.domain.pay.model.valobj.PaymentChannel;
import top.yaofengqiao.springcloudsimple.payment.biz.domain.pay.model.valobj.PaymentType;

/**
 * @author yfq
 * @date 2024/6/14 17:59
 * @description 支付宝支付客户端
 */
@Slf4j
@Service
public class AlipayPaymentClient implements IPaymentClient {
    //应用ID
    private static final String APP_ID = "9021000134638488";
    //应用私钥
    private static final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCLU0EKtuAt2jUUFj5k3nNZAfAyp3EJcU/+iHKGskp9qFQJJudwj2A6VCqTjGoUQeymXIqj6fNdr9ZDMdcmEGQurECG7HK9ayTRA2skwXtSI3Bm5s7vcGixpI7W2yNiU3MJ/y+zpskWqSEt9P5CPeimlghqeSCEElD9qrDUhho7QhSXcky1hCee4/4vPZ0sT+CFw88uwnXuHEXWnht3bOjoR36TOOLP7Nwa2iyLyeT4dO5ath7Armw34irCHjRnKEIUMAwWNu59aYPYJOYyNFznTriooHr6vO4gpFvHTyjs1Lc1m8xpWC1I0Ygjaum3+CBAvkrf0tyvWiNClt9brxjLAgMBAAECggEAQANVa/XQFGEgaAU8T54BQ1Dnqm5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UALyqb71rf0PdyX3H/4uQcXjw4LZThDM/HlfrtiIQ93ond7Q9PHl4gxe9O5E4AYtgQlBJbr35r5s7uxd8Q5WZWd6B8LScaRcVi56Uy+uHK";
    //支付宝公钥
    private static final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAix1IdQk6qwL+1+7duH/h/6RfgqFethCh2L8u4rJiiq0FzJka2QqBuFWKSm8sXKK+tTb37ieQ/LCWZUwuNusbgZZdSaGw7ntioBpYyjxGQVPTlNFdoDsT1ImdHT4SY343KgQCyAfYQPkiZ8V6GYfF/msAqGyQqUlI29iVH1l95AS+7Sl0rceR8s7Un46hoB6ROacuQJF+q4oytl3icsFESk0r22V3EcD2dPs+Yez6dQqS/iKfou6QMseqAdbMIbkHFRxrNUVl2HszHrZQUpxKEnzoW1J/wNx9MFhWQjoEN3vV1TsmUecpPmHEPw8alQ0AvAfiTEEHlVjJDWY3FZabtwIDAQAB";
    //支付宝支付网关url
    private static final String SERVER_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";

    private final AlipayClient alipayClient = new DefaultAlipayClient(SERVER_URL, APP_ID, APP_PRIVATE_KEY, "json",
            "utf-8", ALIPAY_PUBLIC_KEY, "RSA2");

    @Override
    public PaymentChannel payChannel() {
        return PaymentChannel.ALIPAY;
    }

    @Override
    public PaymentApplyResult paymentApply(PaymentApplyRequest request) {
        PaymentType payType = request.getPayType();
        switch (payType) {
            case WEB:
                return webPayApply(request);
            case QR_CODE:
            case QR_CODE_LINK:
            default:
                throw new AppException(ResponseCode.NOT_SUPPORT_PAY_TYPE);
        }
    }

    private PaymentApplyResult webPayApply(PaymentApplyRequest request) {
        try {
            AlipayTradePagePayRequest tradePagePayRequest = buildAlipayTradePagePayRequest(request);
            AlipayTradePagePayResponse response = alipayClient.pageExecute(tradePagePayRequest);
            if (!response.isSuccess()) {
                log.error("支付宝web支付申请失败：request：{}", JSON.toJSONString(request));
                return PaymentApplyResult.builder().success(false).build();
            }

            String body = response.getBody();
            return PaymentApplyResult.builder()
                    .success(true)
                    .contentType("script")
                    .content(body)
                    .build();
        } catch (Exception e) {
            log.error("支付宝web支付申请失败：request：{}", JSON.toJSONString(request));
            return PaymentApplyResult.builder().success(false).build();
        }
    }

    private AlipayTradePagePayRequest buildAlipayTradePagePayRequest(PaymentApplyRequest request) {
        AlipayTradePagePayRequest tradePagePayRequest = new AlipayTradePagePayRequest();
        //异步回调地址
        tradePagePayRequest.setNotifyUrl("");
        //支付成功后返回的页面地址
        tradePagePayRequest.setReturnUrl("");

        JSONObject bizContent = new JSONObject();
        //订单号
        bizContent.put("out_trade_no", request.getOrderNo());
        //订单金额
        bizContent.put("total_amount", request.getAmount());
        //订单标题
        bizContent.put("subject", request.getSubject());
        //订单超时时间
        bizContent.put("timeout_express", "15m");
        //web支付传FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        tradePagePayRequest.setBizContent(bizContent.toString());

        return tradePagePayRequest;
    }

}
